package com.zjny.helper;

import com.zjny.util.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;

/**
 * packageName com.zjny.helper
 *
 * @author cui haida
 * @version JDK 8
 * 2025/6/18
 */
@Component
@Slf4j
public class ThreadPoolHelper {

    /**
     * 线程池
     */
    private final Executor threadPoolExecutor;

    public ThreadPoolHelper(@Qualifier("threadPoolTaskExecutor") Executor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }


    /**
     * 任务执行
     * @param task 要执行的runnable任务
     */
    public void executeTask(Runnable task) {
        threadPoolExecutor.execute(task);
    }

    /**
     * 任务执行
     * @param task 要执行的callable任务
     */
    public Future<?> submitTask(Runnable task) {
        if (threadPoolExecutor instanceof ThreadPoolTaskExecutor) {
            return ((ThreadPoolTaskExecutor) threadPoolExecutor).submit(task);
        } else {
            throw new UnsupportedOperationException("不支持的类型 - callable");
        }
    }

    /**
     * 关闭线程池
     */
    public void shutdown() {
        if (threadPoolExecutor instanceof ThreadPoolTaskExecutor) {
            ThreadUtils.shutdownAndAwaitTermination(((ThreadPoolTaskExecutor) threadPoolExecutor).getThreadPoolExecutor());
        } else {
            throw new UnsupportedOperationException("不支持的类型 - shutdown");
        }
    }

    /**
     * 异步执行一个无返回值的任务。
     *
     * @param task 异步任务
     */
    public CompletableFuture<Void> executeAsync(Runnable task) {
        return CompletableFuture.runAsync(task, threadPoolExecutor);
    }
}